document.addEventListener('DOMContentLoaded', function() {
    const fileInput = document.getElementById('fileInput');
    const resultDiv = document.getElementById('result');
    const historyList = document.getElementById('historyList');
    
    // 检测设备类型
    const isMobile = window.innerWidth <= 768;
    
    // 移动端变量
    const formatSupport = document.querySelector('.format-support');
    const largeIcon = document.querySelector('.large-icon');
    let currentMode = 'word2pdf'; // 默认模式
    
    // 桌面端变量
    const desktopToolItems = document.querySelectorAll('.tool-item');
    const desktopUploadBtn = document.querySelector('.upload-btn');
    const desktopUploadBox = document.querySelector('.upload-box');
    
    // 初始化事件监听
    if (isMobile) {
        initMobileEvents();
    } else {
        initDesktopEvents();
    }
    
    // 移动端事件初始化
    function initMobileEvents() {
        const chooseFileBtn = document.querySelector('.choose-file-btn');
        
        // 点击选择文件按钮
        chooseFileBtn.addEventListener('click', function() {
            fileInput.click();
        });
        
        // 添加转换模式切换
        document.getElementById('word2pdf').addEventListener('click', function() {
            switchMode('word2pdf');
        });
        
        document.getElementById('pdf2word').addEventListener('click', function() {
            switchMode('pdf2word');
        });
        
        // 底部导航切换
        const navItems = document.querySelectorAll('.nav-item');
        navItems.forEach(item => {
            item.addEventListener('click', function() {
                navItems.forEach(i => i.classList.remove('active'));
                this.classList.add('active');
            });
        });
    }
    
    // 桌面端事件初始化
    function initDesktopEvents() {
        // 工具组标题点击事件（展开/折叠）
        const toolHeaders = document.querySelectorAll('.tool-header');
        toolHeaders.forEach(header => {
            header.addEventListener('click', function() {
                const toolList = this.nextElementSibling;
                const arrow = this.querySelector('.arrow');
                
                if (toolList.style.display === 'none') {
                    toolList.style.display = 'block';
                    arrow.textContent = '▼';
                } else {
                    toolList.style.display = 'none';
                    arrow.textContent = '▶';
                }
            });
        });

        // 工具项点击事件
        desktopToolItems.forEach(item => {
            item.addEventListener('click', function() {
                desktopToolItems.forEach(i => i.classList.remove('active'));
                this.classList.add('active');
                
                // 更新模式
                currentMode = this.getAttribute('data-mode');
                
                // 更新UI
                updateDesktopUI(currentMode);
            });
        });
        
        // 上传按钮点击事件
        desktopUploadBtn.addEventListener('click', function() {
            fileInput.click();
        });
        
        // 拖拽文件
        desktopUploadBox.addEventListener('dragover', function(e) {
            e.preventDefault();
            desktopUploadBox.style.borderColor = '#0066ff';
        });
        
        desktopUploadBox.addEventListener('dragleave', function() {
            desktopUploadBox.style.borderColor = '#ccc';
        });
        
        desktopUploadBox.addEventListener('drop', function(e) {
            e.preventDefault();
            desktopUploadBox.style.borderColor = '#ccc';
            
            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                handleFileUpload(e.dataTransfer.files[0]);
            }
        });
    }
    
    // 更新桌面UI
    function updateDesktopUI(mode) {
        const conversionTitle = document.querySelector('.conversion-title');
        const conversionDesc = document.querySelector('.conversion-desc');
        const uploadTip = document.querySelector('.upload-tip');
        
        if (mode === 'pdf2word') {
            conversionTitle.textContent = 'PDF转Word';
            conversionDesc.textContent = '格式不变，可编辑，把PDF转换为Word文档';
            uploadTip.textContent = '点击上传PDF文档或拖拽PDF文档至此，支持格式：.pdf';
            fileInput.setAttribute('accept', '.pdf');
        } else {
            conversionTitle.textContent = 'Word转PDF';
            conversionDesc.textContent = '格式不变，高质量，把Word转换为PDF文档';
            uploadTip.textContent = '点击上传Word文档或拖拽Word文档至此，支持格式：.doc/.docx';
            fileInput.setAttribute('accept', '.doc,.docx');
        }
    }
    
    // 移动端模式切换
    function switchMode(mode) {
        currentMode = mode;
        
        if (mode === 'word2pdf') {
            formatSupport.textContent = '支持.doc/.docx格式文件';
            largeIcon.textContent = 'DOC';
            largeIcon.className = 'doc-icon large-icon';
            fileInput.setAttribute('accept', '.doc,.docx');
        } else {
            formatSupport.textContent = '支持.pdf格式文件';
            largeIcon.textContent = 'PDF';
            largeIcon.className = 'pdf-icon large-icon';
            fileInput.setAttribute('accept', '.pdf');
        }
    }
    
    // 文件选择变化
    fileInput.addEventListener('change', function() {
        if (fileInput.files.length) {
            handleFileUpload(fileInput.files[0]);
        }
    });
    
    // 处理文件上传
    function handleFileUpload(file) {
        const fileName = file.name.toLowerCase();
        let apiEndpoint = '';
        
        // 根据当前模式选择API端点
        if (currentMode === 'pdf2word') {
            if (!fileName.endsWith('.pdf')) {
                showResult('<p class="error">请上传PDF文件</p>');
                return;
            }
            apiEndpoint = '/api/pdf2word';
        } else {
            if (!fileName.endsWith('.doc') && !fileName.endsWith('.docx')) {
                showResult('<p class="error">请上传Word文件(.doc或.docx)</p>');
                return;
            }
            apiEndpoint = '/api/word2pdf';
        }
        
        const formData = new FormData();
        formData.append('file', file);
        
        // 显示上传中状态
        showResult('<p>文件上传中，请稍候...</p>');
        
        // 发送到服务器
        fetch(apiEndpoint, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showResult('<p class="success">转换成功！</p>');
                
                // 添加到历史记录
                if (isMobile) {
                    addToHistory(file.name, result.pdfUrl);
                } else {
                    // 桌面端显示下载链接
                    document.getElementById('desktop-result').innerHTML = `
                        <a href="${result.pdfUrl}" class="download-btn" download>下载文件</a>
                    `;
                }
            } else {
                showResult(`<p class="error">转换失败：${result.message}</p>`);
            }
        })
        .catch(error => {
            showResult(`<p class="error">请求失败：${error.message}</p>`);
        });
    }
    
    // 显示结果
    function showResult(html) {
        resultDiv.innerHTML = html;
        if (!isMobile) {
            document.getElementById('desktop-result').innerHTML = html;
        }
    }
    
    // 添加到历史记录
    function addToHistory(fileName, fileUrl) {
        const now = new Date();
        const dateStr = `${now.getFullYear()}/${now.getMonth()+1}/${now.getDate()} 上午${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
        
        const historyItem = document.createElement('div');
        historyItem.className = 'history-item';
        
        // 根据文件类型设置图标
        const isDoc = fileName.toLowerCase().endsWith('.doc') || fileName.toLowerCase().endsWith('.docx');
        const iconClass = isDoc ? 'doc-icon' : 'pdf-icon';
        const iconText = isDoc ? 'DOC' : 'PDF';
        
        historyItem.innerHTML = `
            <div class="history-icon ${iconClass}">${iconText}</div>
            <div class="history-info">
                <div class="history-name">${fileName}</div>
                <div class="history-date">${dateStr}</div>
            </div>
            <button class="history-action" data-url="${fileUrl}">打开</button>
        `;
        
        // 添加到历史记录列表的顶部
        if (historyList.firstChild) {
            historyList.insertBefore(historyItem, historyList.firstChild);
        } else {
            historyList.appendChild(historyItem);
        }
        
        // 添加打开按钮事件
        historyItem.querySelector('.history-action').addEventListener('click', function() {
            window.open(this.getAttribute('data-url'), '_blank');
        });
    }
}); 